var http = require('../../utils/http.js');
var config = require('../../utils/config.js');
var util = require('../../utils/util.js');

Page({
    data: {
        activity: null,
        prod: null,      
        countdown: '',
        sku:'',
        timer: null,
        isSeckilling: false,
    },

    onLoad: function (options) {
        this.setData({
            activityId: options.activityId
        });
        this.loadSeckillDetail();
    },

    onUnload: function () {
        if (this.data.timer) {
            clearInterval(this.data.timer);
        }
    },

    // 加载秒杀详情
    loadSeckillDetail: function () {
        wx.showLoading({ title: '加载中...' });

        // 获取活动详情
        var activityParams = {
            url: "/seckill-service/seckill/" + this.data.activityId,
            method: "GET",
            data: {},
            callBack: (res) => {
                wx.hideLoading();
                this.setData({
                    activity: res
                });

                // 获取商品详情
                this.loadProductDetail(res.prodId,res.skuId);

                // 启动倒计时
                this.startCountdown();
            }
        };
        http.request(activityParams);
    },

    // 加载商品详情
    loadProductDetail: function (prodId,skuId) {
        var params = {
            url: "/product-service/prod/prod/seckillProd/info",
            method: "GET",
            data: {
              prodId:prodId,
              skuId:skuId
            },
            callBack: (res) => {          
              var imgStrs = res.imgs;
              console.log(imgStrs)
              var imgs = imgStrs.split(",");
              console.log(imgs)
              var content = util.formatHtml(res.content);
              var skuStrs = res.skuList[0].properties
              console.log(sku)
              var sku = skuStrs.replaceAll(";", " ");
                this.setData({
                    prod: res,
                    imgs: imgs,
                    content: content,
                    sku: sku
                });
            }
        };
        http.request(params);
    },

    // 启动倒计时
    startCountdown: function () {
        if (this.data.timer) {
            clearInterval(this.data.timer);
        }

        this.data.timer = setInterval(() => {
            this.updateCountdown();
        }, 1000);

        this.updateCountdown();
    },

    // 更新倒计时显示
    updateCountdown: function () {
        if (!this.data.activity) return;

        const now = new Date().getTime();
        const startTime = new Date(this.data.activity.startTime).getTime();
        const endTime = new Date(this.data.activity.endTime).getTime();

        let countdown = '';
        if (now < startTime) {
            // 活动未开始
            const diff = startTime - now;
            countdown = this.formatTime(diff) + '后开始';
        } else if (now >= startTime && now <= endTime) {
            // 活动进行中
            const diff = endTime - now;
            countdown = this.formatTime(diff) + '后结束';
        } else {
            // 活动已结束
            countdown = '活动已结束';
            if (this.data.timer) {
                clearInterval(this.data.timer);
            }
        }

        this.setData({
            countdown: countdown
        });
    },

    // 格式化时间
    formatTime: function (milliseconds) {
        const seconds = Math.floor(milliseconds / 1000);
        const days = Math.floor(seconds / (24 * 3600));
        const hours = Math.floor((seconds % (24 * 3600)) / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;

        if (days > 0) {
            return `${days}天${hours}小时`;
        }
        return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },

    // 执行秒杀
    executeSeckill: function () {
        if (this.data.isSeckilling) return;

        // 检查活动状态
        const now = new Date().getTime();
        const startTime = new Date(this.data.activity.startTime).getTime();
        const endTime = new Date(this.data.activity.endTime).getTime();

        if (now < startTime) {
            wx.showToast({
                title: '活动尚未开始',
                icon: 'none'
            });
            return;
        }

        if (now > endTime) {
            wx.showToast({
                title: '活动已结束',
                icon: 'none'
            });
            return;
        }

        this.setData({
            isSeckilling: true
        });

        wx.showLoading({ title: '正在秒杀...' });

        var params = {
            url: "/seckill-service/seckill/" + this.data.activityId + "/execute",
            method: "POST",
            data: {},
            callBack: (res) => {
                wx.hideLoading();
                this.setData({
                    isSeckilling: false
                });

                if (res.code === 200) {
                    wx.showToast({
                        title: '秒杀成功!',
                        icon: 'success'
                    });

                    // 跳转到订单页面
                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/order-detail/order-detail?orderId=' + res.data.orderId
                        });
                    }, 1500);
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            },
            errorCallBack: () => {
                wx.hideLoading();
                this.setData({
                    isSeckilling: false
                });
                wx.showToast({
                    title: '网络异常，请重试',
                    icon: 'none'
                });
            }
        };
        http.request(params);
    }
});